﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using CP.Entities;
using CP.Controllers.GPM;
using DevExpress.XtraEditors;
using CP.Utility;
using DevExpress.XtraTreeList.Nodes;
using System.IO;
using DevExpress.XtraTreeList;
using DevExpress.XtraSplashScreen;

namespace GPM
{
    public partial class FrmWebpartInital : BaseCommForm
    {
        public FrmWebpartInital()
        {
            InitializeComponent();
            this.BarComponents = components;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (this.lookupParentID.EditValue == null)
            {
                ExMessageBox.Show("提示信息：模块名称不能为空！", AppSetter.SoftName);
                return;
            }

            if (this.treeFileList.Nodes.Count == 0)
            {
                ExMessageBox.Show("提示信息：文件列表为空！", AppSetter.SoftName);
                return;
            }

            SplashScreenManager.ShowForm(typeof(SplashScreenProgressBar));
            WebpartController controller = new WebpartController();
            int success = 0;
            int total = treeFileList.Nodes.Count;
            string errmsg = "";
            for (int i = 0; i < total; i++)
            {
                try
                {
                    Webpart webpart = new Webpart();
                    webpart.module_id = Convert.ToInt32(this.lookupParentID.EditValue);
                    webpart.form_name = treeFileList.Nodes[i].GetDisplayText("filename");
                    //controller.AddWebpart(webpart, treeFileList.Nodes[i].Tag == null ?
                    //                         "" : treeFileList.Nodes[i].Tag.ToString());
                    success += 1;
                }
                catch (Exception ex)
                {
                    errmsg += ex.Message + ";";
                }

                SplashScreenManager.Default.SendCommand(
                       SplashScreenProgressBar.SplashScreenCommand.SetProgress,
                       (i + 1) * 100 / total);
                treeFileList.Nodes[i].Tag = 1;
            }

            for (int i = total - 1; i >= 0; i--)
            {
                if (treeFileList.Nodes[i].Tag.ToString() == "1")
                {
                    treeFileList.Nodes.RemoveAt(i);
                }
            }

            ExMessageBox.Show("提示信息：成功初始化[" + success +
                "]个组件，失败[" + (total - success).ToString() + "]  错误信息：" + errmsg,
                AppSetter.SoftName);

            SplashScreenManager.CloseForm();
        }

        private void FrmWebpartInital_Load(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "控件文件 (*.ascx)|*.ascx";
            openFileDialog1.InitialDirectory = Application.StartupPath;
            openFileDialog1.Title = "请选择用户控件文件";
            openFileDialog1.InitialDirectory = Application.StartupPath;

            ModuleController mc = new ModuleController();
            this.lookupParentID.Properties.DataSource = mc.GetAllModules();
        }

        private void OpenFolder(DirectoryInfo dinfo)
        {
            //遍历文件夹
            foreach (DirectoryInfo folder in dinfo.GetDirectories())
                OpenFolder(folder);
            //遍历文件
            foreach (FileInfo file in dinfo.GetFiles())
            {
                if (string.IsNullOrEmpty(file.FullName))
                    continue;

                if (string.IsNullOrEmpty(file.Name))
                    continue;
                if (IsExists(treeFileList.Nodes, file.Name))
                    continue;
                TreeListNode node = treeFileList.AppendNode(
                    new object[] { file.Name }, -1, -1, -1, 6);
                node.Tag = file.FullName;
            }
        }

        private bool IsExists(TreeListNodes nodes, string value)
        {
            foreach (TreeListNode node in nodes)
            {
                if (node.GetDisplayText("filename") == value)
                    return true;
                IsExists(node.Nodes, value);
            }
            return false;
        }

        private void btnOpenFile_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    int i = 0;
                    SplashScreenManager.ShowForm(typeof(SplashScreenProgressBar));
                    foreach (string fullname in openFileDialog1.FileNames)
                    {
                        if (string.IsNullOrEmpty(fullname))
                            continue;
                        string filename = System.IO.Path.GetFileName(fullname);
                        if (string.IsNullOrEmpty(filename))
                            continue;
                        if (IsExists(treeFileList.Nodes, filename))
                            continue;
                        TreeListNode node = treeFileList.AppendNode(
                            new object[] { filename }, -1, -1, -1, 6);
                        node.Tag = fullname;
                        SplashScreenManager.Default.SendCommand(
                                SplashScreenProgressBar.SplashScreenCommand.SetProgress,
                                (i + 1) * 100 / openFileDialog1.FileNames.Length);
                        i++;
                    }
                    SplashScreenManager.CloseForm();
                }
            }
            catch (Exception ex)
            {
                ExMessageBox.Show(ex.Message, AppSetter.SoftName);
            }
        }

        private void btnOpenFolder_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (String.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                    {
                        ExMessageBox.Show("没有选中文件夹!", AppSetter.SoftName);
                        return;
                    }

                    DirectoryInfo folder = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
                    OpenFolder(folder);
                }
            }
            catch (Exception ex)
            {
                ExMessageBox.Show(ex.Message, AppSetter.SoftName);
            }
        }

        private void btnClear_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.treeFileList.Nodes.Clear();
        }

        private void treeFileList_Click(object sender, EventArgs e)
        {
            TreeListHitInfo t = treeFileList.CalcHitInfo(p);
            if (t.HitInfoType == HitInfoType.Cell)
            {
                if (t.Column.FieldName == "operateflag")
                {
                    treeFileList.Nodes.Remove(t.Node);
                }
            }
        }

        private Point p;

        private void treeFileList_MouseDown(object sender, MouseEventArgs e)
        {
            p.X = e.X;
            p.Y = e.Y;
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (this.treeFileList.Nodes.Count == 0)
            {
                ExMessageBox.Show("提示信息：文件列表为空！", AppSetter.SoftName);
                return;
            }

            SplashScreenManager.ShowForm(typeof(SplashScreenProgressBar));
            WebpartController controller = new WebpartController();
            int success = 0;
            int total = treeFileList.Nodes.Count;
            string errmsg = "";
            for (int i = 0; i < total; i++)
            {
                try
                {
                    Webpart webpart = new Webpart();
                    //webpart.module_id = Convert.ToInt32(this.lookupParentID.EditValue);
                    webpart.form_name = treeFileList.Nodes[i].GetDisplayText("filename");
                    controller.AddWebpartButton(webpart, treeFileList.Nodes[i].Tag == null ?
                                             "" : treeFileList.Nodes[i].Tag.ToString());
                    //#if (DEBUG)
                    //                    Console.WriteLine(((i + 1) * 100m / total).ToString() + "," + ((int)(i + 1) * 100 / total).ToString());
                    //#endif
                    SplashScreenManager.Default.SendCommand(
                        SplashScreenProgressBar.SplashScreenCommand.SetProgress,
                        (i + 1) * 100 / total);
                    treeFileList.Nodes[i].Tag = 1;
                    success += 1;
                }
                catch (Exception ex)
                {
                    errmsg += ex.Message + ";";
                    ReallySimpleLog.WriteSimpleLog(treeFileList.Nodes[i].GetDisplayText("filename"));
                }
            }

            for (int i = total - 1; i >= 0; i--)
            {
                if (treeFileList.Nodes[i].Tag.ToString() == "1")
                {
                    treeFileList.Nodes.RemoveAt(i);
                }
            }

            ExMessageBox.Show("提示信息：成功初始化[" + success +
                "]个组件，失败[" + (total - success).ToString() + "]  错误信息：" + errmsg,
                AppSetter.SoftName);

            SplashScreenManager.CloseForm();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            if (this.treeFileList.Nodes.Count == 0)
            {
                ExMessageBox.Show("提示信息：文件列表为空！", AppSetter.SoftName);
                return;
            }

            SplashScreenManager.ShowForm(typeof(SplashScreenProgressBar));
            WebpartController controller = new WebpartController();
            int success = 0;
            int total = treeFileList.Nodes.Count;
            string errmsg = "";
            for (int i = 0; i < total; i++)
            {
                try
                {
                    Webpart webpart = new Webpart();
                    webpart.form_name = treeFileList.Nodes[i].GetDisplayText("filename");
                    IList<string> files = controller.AddWebpartLinkButton(webpart, treeFileList.Nodes[i].Tag == null ?
                                             "" : treeFileList.Nodes[i].Tag.ToString());
                    if (files.Count > 0)
                    {
                        foreach (string file in files)
                            ReallySimpleLog.WriteSimpleLog(file);
                    }
                    SplashScreenManager.Default.SendCommand(
                        SplashScreenProgressBar.SplashScreenCommand.SetProgress,
                        (i + 1) * 100 / total);

                }
                catch (Exception ex)
                {
                    errmsg += ex.Message + ";";
                    ReallySimpleLog.WriteSimpleLog(treeFileList.Nodes[i].GetDisplayText("filename"));
                }
            }


            ExMessageBox.Show("提示信息：找到[" + success +
                "]个含有linkbutton组件",
                AppSetter.SoftName);

            SplashScreenManager.CloseForm();
        }
    }
}
